
package com.kamikaze.lamg;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Utils {
    // public ArrayList<MovieInfo> loadMoviesInfo(Context context) {
    // ArrayList<MovieInfo> movies = new ArrayList<MovieInfo>();
    // InputStream in = context.getResources().openRawResource(R.raw.info);
    // BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    // StringBuilder sb = new StringBuilder();
    // String line = null;
    // try {
    // while ((line = reader.readLine()) != null) {
    // sb.append(line);
    // }
    // JSONArray array = new JSONArray(sb.toString());
    // MovieInfo movieInfo;
    // for (int i = 0; i < array.length(); i++) {
    // JSONObject jsonObject = array.optJSONObject(i);
    // if (jsonObject != null) {
    // movieInfo = new MovieInfo();
    // movieInfo.title = jsonObject.optString("title");
    // String frontCoverStr = jsonObject.optString("frontcover");
    // if (frontCoverStr != null
    // && !"".equals(frontCoverStr.trim())) {
    // byte[] frontCoverBytes = Base64.decode(frontCoverStr,
    // Base64.DEFAULT);
    // if (frontCoverBytes != null) {
    // movieInfo.frontCover = BitmapFactory
    // .decodeByteArray(frontCoverBytes, 0,
    // frontCoverBytes.length);
    // }
    // }
    // movieInfo.actress = jsonObject.optString("actress");
    // movieInfo.publishDate = jsonObject
    // .optString("publish_data");
    // movieInfo.publisher = jsonObject.optString("publisher");
    // movieInfo.feature = jsonObject.optString("feature");
    //
    // movies.add(movieInfo);
    // }
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // return movies;
    // }

    // private void createPicData() {
    // int[] images = new int[] { R.drawable.m1, R.drawable.m2, R.drawable.m3,
    // R.drawable.m4, R.drawable.m5, R.drawable.m6, R.drawable.m7,
    // R.drawable.m8 };
    // FileWriter fw = null;
    // try {
    // fw = new FileWriter(new File("/sdcard/xxx.txt"));
    // for (int i = 0; i < images.length; i++) {
    // Bitmap bm = BitmapFactory.decodeResource(this.getResources(),
    // images[i]);
    // fw.write(i
    // + "::"
    // + Base64.encodeToString(Bitmap2Bytes(bm),
    // Base64.DEFAULT) + "\n\n\n\n");
    // }
    // fw.flush();
    // fw.close();
    // } catch (IOException e) {
    // e.printStackTrace();
    // }
    // }

    // private byte[] Bitmap2Bytes(Bitmap bm) {
    // ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    // return baos.toByteArray();
    // }
    public static void copyFile(String path, InputStream in, boolean overlay) {
        File file = new File(path);
        copyFile(file, in, overlay);
    }

    public static void copyFile(String path, byte[] data, boolean overlay) {
        File file = new File(path);
        copyFile(file, data, overlay);
    }

    private static void copyFile(File file, byte[] data, boolean overlay) {

        BufferedOutputStream out = null;
        if (!checkFile(file, overlay)) {
            return;
        }
        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            out.write(data);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static boolean checkFile(File file, boolean overlay) {
        try {
            if (file.exists()) {
                if (!overlay) {
                    return false;
                } else {
                    file.delete();
                }
            } else {
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                if (!file.exists()) {
                    file.createNewFile();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    public static void copyFile(File file, InputStream in, boolean overlay) {
        if (!checkFile(file, overlay)) {
            return;
        }
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static boolean getNetState(ConnectivityManager manager) {
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo == null)
            return false;
        return networkInfo.isConnected();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int computeSampleSize(BitmapFactory.Options options,

    int minSideLength, int maxNumOfPixels) {

        int initialSize = computeInitialSampleSize(options, minSideLength,

        maxNumOfPixels);

        int roundedSize;

        if (initialSize <= 8) {

            roundedSize = 1;

            while (roundedSize < initialSize) {

                roundedSize <<= 1;

            }

        } else {

            roundedSize = (initialSize + 7) / 8 * 8;

        }

        return roundedSize;

    }

    private static int computeInitialSampleSize(BitmapFactory.Options options,

    int minSideLength, int maxNumOfPixels) {

        double w = options.outWidth;

        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 :

        (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));

        int upperBound = (minSideLength == -1) ? 128 :

        (int) Math.min(Math.floor(w / minSideLength),

        Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {

            // return the larger one when there is no overlapping zone.

            return lowerBound;

        }

        if ((maxNumOfPixels == -1) &&

        (minSideLength == -1)) {

            return 1;

        } else if (minSideLength == -1) {

            return lowerBound;

        } else {

            return upperBound;

        }

    }
}
